package com.tom.appa;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tom.joke.UserAidl;

// A应用端。client端。
public class MainActivity extends AppCompatActivity {
    private ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("Service", "onServiceConnected "+ name.getClassName());
            // 连接好了
            mUserAidl = UserAidl.Stub.asInterface(service);
            Toast.makeText(MainActivity.this, "onServiceConnected:" , Toast.LENGTH_LONG).show();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("Service", "onServiceDisconnected "+ name.getClassName());
            // 断开连接
            Toast.makeText(MainActivity.this, "onServiceDisconnected:" , Toast.LENGTH_LONG).show();
        }
    };
    // 客户端一定要获取aidl的实例，这个实例时服务端返回的。
    private UserAidl mUserAidl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindService();
    }

    @Override
    protected void onDestroy() {
        unBindService();
        super.onDestroy();
    }
    private void bindService() {
        Intent intent = new Intent();
        intent.setAction("com.study.aidl.user");
        // 5.0后，为了安全问题，禁止了隐式声明Intent来启动Service
        // 也禁止使用 IntentFilter，否则就会抛异常。
        intent.setPackage("com.tom.joke"); // 目标apk的包名
        bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);
    }
    public void unBindService() {
        if (mUserAidl != null) {
            unbindService(mServiceConn);
        }
    }

    // 获取用户名，获取密码
    public void getUserName(View view) {
        if (mUserAidl != null) {
            try {
                String name = mUserAidl.getUserName();
                Toast.makeText(this, "userName:" + name, Toast.LENGTH_LONG).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
    public void getPassword(View view) {
        if (mUserAidl != null) {
            try {
                String password = mUserAidl.getUserPwd();
                Toast.makeText(this, "password:" + password, Toast.LENGTH_LONG).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}
